package net.yunxinyong.sign.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.yunxinyong.sign.aop.CECException;
import net.yunxinyong.sign.entity.SignAdmin;
import net.yunxinyong.sign.entity.SignAdminExample;
import net.yunxinyong.sign.mapper.SignAdminMapper;
import net.yunxinyong.sign.mapper.SignRecordMapper;
import net.yunxinyong.sign.service.ProjectManagerService;
import net.yunxinyong.sign.service.RecordService;
import net.yunxinyong.sign.utils.ListUtils;
import net.yunxinyong.sign.utils.PageBean;
import net.yunxinyong.sign.utils.PasswordUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 *@describe 人员管理相关模块
 *@author  ttbf
 *@date  2018/10/29
 */
@Service
public class ProjectManagerServiceImpl implements ProjectManagerService {

    @Autowired
    private SignAdminMapper signAdminMapper;
    @Autowired
    private SignRecordMapper signRecordMapper;
    @Autowired
    private RecordService recordService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public SignAdmin insert(SignAdmin signAdmin,Integer id) {
        //判断账号是否已存在
        SignAdminExample signAdminExample = new SignAdminExample();
        if (signAdmin.getPhone() == null){
            throw new CECException(505,"参数有误");
        }
        signAdminExample.createCriteria().andPhoneEqualTo(signAdmin.getPhone());
        List<SignAdmin> signAdmins = signAdminMapper.selectByExample(signAdminExample);

        if (signAdmin.getRole() != null && signAdmin.getRole().equals("普查员") && signAdmin.getRole().equals("root")){
            throw new CECException(505,"没有操作权限");
        }
        if (signAdmin.getArea() == null){
            signAdmin.setArea(signAdminMapper.selectByPrimaryKey(id).getArea());
        }
        if (signAdmin.getRole() == null){
            signAdmin.setRole("普查员");
        }
        //判断是否有操作权限
        if (jurisdiction(signAdmin,id)){
            if (!ListUtils.isEmpty(signAdmins)){
                throw new CECException(505,"账号已存在");
            }
            String alphanumeric = RandomStringUtils.randomAlphanumeric(10);
            signAdmin.setHash(alphanumeric);
            try {
                signAdmin.setPassword(PasswordUtil.encrypt(signAdmin.getPassword(), alphanumeric));
            } catch (Exception e) {
                throw new CECException(505,e.getMessage());
            }
            signAdmin.setCreateTime(new Date());
            signAdmin.setUpdateTime(new Date());
            boolean b = signAdminMapper.insertSelective(signAdmin) > 0;
            //添加操作记录
            boolean insert = recordService.insert(id, null, signAdmin.getId(), 2);
            if (!b || !insert){
                throw new CECException(505,"操作失败");
            }
            return signAdmin;
        }else {
            throw new CECException(505,"没有操作权限");
        }

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public SignAdmin update(SignAdmin signAdmin,Integer id) {

        //判断是否有操作权限
        if (jurisdiction(signAdmin,id)){
            //如果修改密码
            if (signAdmin.getPassword() != null && !signAdmin.getPassword().equals("")){
                String alphanumeric = RandomStringUtils.randomAlphanumeric(10);
                signAdmin.setHash(alphanumeric);
                try {
                    signAdmin.setPassword(PasswordUtil.encrypt(signAdmin.getPassword(), alphanumeric));
                } catch (Exception e) {
                    throw new CECException(505,e.getMessage());
                }
            }else {
                signAdmin.setPassword(null);
            }
            signAdmin.setPhone(null);
            signAdmin.setUpdateTime(new Date());
            boolean b = signAdminMapper.updateByPrimaryKeySelective(signAdmin) > 0;
            //添加操作记录
            boolean insert = recordService.insert(id, null, signAdmin.getId(), 3);
            if (!b || !insert){
                throw new CECException(505,"操作失败");
            }
            return signAdmin;
        }else {
            throw new CECException(505,"没有操作权限");
        }
    }

    @Override
    public PageBean getList(SignAdmin signAdmin,Integer id, int page, int rows) {
        SignAdminExample signAdminExample = new SignAdminExample();
        SignAdminExample.Criteria criteria = signAdminExample.createCriteria();
        //判断是否有操作权限
        if (signAdminMapper.selectByPrimaryKey(id).getRole().equals("root")){
            criteria.andRoleNotEqualTo("root");
        }else if (signAdminMapper.selectByPrimaryKey(id).getRole().equals("管理员")){
            criteria.andRoleEqualTo("普查员");
        }else {
            criteria.andIdEqualTo(id);
        }
        //根据操作员id查询
        if (signAdmin.getId() != null){
            criteria.andIdEqualTo(signAdmin.getId());
        }
        //根据普查员账号查询
        if (signAdmin.getPhone() != null && !signAdmin.getPhone().equals("")){
            criteria.andPhoneEqualTo(signAdmin.getPhone());
        }
        //根据角色查询
        if (signAdmin.getRole() != null){
            criteria.andRoleEqualTo(signAdmin.getRole());
        }
        //根据区域查询
        if (signAdmin.getArea() != null){
            criteria.andAreaEqualTo(signAdmin.getArea());
        }
        if (page != 0 && rows != 0) {
            PageHelper.startPage(page, rows);
        }
        List<SignAdmin> signAdminList = signAdminMapper.selectByExample(signAdminExample);
        PageBean<SignAdmin> pageBean = new PageBean<>();
        PageInfo<SignAdmin> pageInfo = new PageInfo<>(signAdminList);
        pageBean.setTotal(pageInfo.getTotal());
        pageBean.setTotalPages(pageInfo.getPages());
        pageBean.setPageNumber(pageInfo.getPageNum());
        pageBean.setPageSize(pageInfo.getSize());
        pageBean.setPageDatas(signAdminList);
        return pageBean;
    }


    /**
     * 操作权限判断
     * @param roleAdminSign 被操作人
     * @param id 操作人
     * @return
     */
    private boolean jurisdiction(SignAdmin roleAdminSign,Integer id){
        SignAdmin roleSign = signAdminMapper.selectByPrimaryKey(id);
        String role = roleSign.getRole();
        String roleAdmin = roleAdminSign.getRole();
        String area = roleSign.getArea();
        String areaAdmin = roleAdminSign.getArea();
        //root如果用户为root，拥有所有权限
        if(role.equals("root")){
            return true;
        }
        //判断是都为同一区域
        if (area.equals(areaAdmin)){
            if (role.equals("管理员")){
                if(roleAdmin.equals("普查员")){
                    return true;
                }else {
                    return false;
                }
            }
        }
        return false;
    }
}
